package com.twq.gaoji;

/**
 * @author twq
 * @date 2021/8/23 10:23
 */
//测试生产者消费者  ——————管程法 利用缓冲区
public class TestPC {


    public static void main(String[] args) {
        SyContainner syContainner = new SyContainner();
        new Productor(syContainner).start();
        new Consumer(syContainner).start();

    }

}

//生产者
class Productor extends Thread{
    SyContainner containner;
    public Productor(SyContainner containner){
        this.containner=containner;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {

            containner.push(new Chickern(i));
            System.out.println("生产了"+i+"只鸡");
        }
    }
}
//消费者
class Consumer extends Thread{
    SyContainner containner;
    public Consumer(SyContainner containner){
        this.containner=containner;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了————》"+containner.pop().id+"鸡");
        }
    }
}
//产品
class Chickern{

    int id;
    public Chickern(int id){
        this.id= id;
    }
}

//缓冲区
class SyContainner{

    //需要一个容器大小
    Chickern[] chickerns = new Chickern[10];

    //容器计数器
    int count = 0;

    //生产者放入一个产品
    public synchronized void push (Chickern chickern){

        //如果容器满了 就需要等待消费者消费
        if (count== chickerns.length){
            //通知消费者消费，生产等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //如果没有满。我们就需要丢入产品了
        chickerns[count] = chickern;
        count++;

        //可以通知消费者消费了
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Chickern pop(){
        //能否消费
        if(count == 0){

            try {
                //等待生产者生产
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        Chickern chickern = chickerns[count];

        //吃完了,通知生产者生产
        this.notifyAll();
        return chickern;
    }

}
